# /usr/bin/env python3.6
# -*- encoding: utf-8 -*-
"""
@File    : movie_order_api.py
@Time    : 2020/2/6 0006 13:38
@Author  : zhangbing
@Email   : 18829172841@163.com
@Software: PyCharm
"""
import datetime

import requests
from flask import g
from flask_restful import Resource, reqparse, abort, fields, marshal
from sqlalchemy import or_

from App.apis.api_constant import HTTP_CREATE_OK
from App.apis.movie_user.utils import login_required, required_permission
from App.models.cinema_admin.cinema_hall_model import Hall
from App.models.cinema_admin.cinma_hall_movie_model import HallMovie
from App.models.movie_user.movie_order_model import MovieOrder, ORDER_STATUS_GET, ORDER_STATUS_PAYED_NOT_GET, \
    ORDER_STATUS_NOT_PAY
from App.models.movie_user.movie_user_model import VIP_USER

parse = reqparse.RequestParser()
parse.add_argument("o_hall_movie_id", type=int, help="请选择对应的排挡信息")
parse.add_argument("o_seats", type=str, help="请选择对应的座位")

order_fields = {
    "o_hall_movie_id": fields.Integer,
    "o_seats": fields.String,
    "o_price": fields.Float
}


# 创建订单
class MovieOrdersResource(Resource):
    @login_required
    def post(self):
        args = parse.parse_args()
        o_hall_movie_id = args.get("o_hall_movie_id")
        o_seats = args.get("o_seats")
        # 此处查询到的是支付成功的和正在支付的订单
        movie_orders_buyed = MovieOrder.query.filter(MovieOrder.o_hall_movie_id == o_hall_movie_id).filter(
            or_(MovieOrder.o_status == ORDER_STATUS_GET, MovieOrder.o_status == ORDER_STATUS_PAYED_NOT_GET)).all()
        # 此处处理的是未支付及正在创建的订单和支付失效的订单
        movie_orders_rlock = MovieOrder.query.filter(MovieOrder.o_hall_movie_id == o_hall_movie_id).filter(
            or_(MovieOrder.o_status == ORDER_STATUS_NOT_PAY, MovieOrder.o_time > datetime.datetime.now())).all()
        # 通过 hall_movie_id 获取对应的位置信息
        # MovieOrder 中有o_hall_movie_id 及 hall_movie中的id，中的o_seats 是 hall中的字段
        seats = []
        for movie_orders in movie_orders_buyed:
            sold_seats = movie_orders.o_seats.split("#")
            seats += sold_seats

        for movie_orders in movie_orders_rlock:
            sold_seat = movie_orders.o_seats.split("#")
            seats += sold_seat

        hallmovie = HallMovie.query.get(o_hall_movie_id)
        seats_all = Hall.query.get(hallmovie.h_hall_id).h_seats
        o_seats = o_seats.split("#")
        for seat in o_seats:
            if seat not in seats_all:
                abort(400, msg="该座位不存在")
        for seat in seats:
            if seat in o_seats:
                abort(400, msg="座位已被购买或在或购买中")
        else:
            user = g.user
            movie_order = MovieOrder()
            movie_order.o_hall_movie_id = o_hall_movie_id
            movie_order.o_user_id = user.id
            movie_order.o_seats = "#".join(o_seats)
            movie_order.o_time = datetime.datetime.now() + datetime.timedelta(minutes=15)
            movie_order.o_price = 100.00
            if not movie_order.save():
                abort(400, msg="订单创建失败！")
            '''
            并发导致的锁问题：
            1  变并行为串行 
                通过将其添加到队列的方式来完成
            2 使用锁机制
                1 乐观锁
                    通过在插入之前查询和插入之后查询的方式完成对锁的处理
                    
                2 悲观锁 
                    通过在插入之前对表进行操作，并在插入之后进行处理的方式完成处理
                    
                    db.session.with_lockmode("update")  # 此处是加更新锁
                    db.session.Query(MovieOrder).with_lockmode("update") # 此处是对某个表进行加锁处理
                    db.session.commit()  # 此处是解锁
            事务  
            基本的处理方式
            try:
                movie_order1=MovieOrder.query.get(1)
                movie_order2=MovieOrder.query.get(2)
                db.session.delete(movie_order1)
                db.session.delete(movie_order1)
            except  Exception  e:
                print (e)
                db.session.rollback()
            else:
                db.session.commit()
            
            '''
            response = requests.get("192.168.3.100/user/pay", order_id=movie_order.id, uname="中国",
                                    sumprice=movie_order.o_price)

            return {
                "msg": "订单创建成功！！",
                "status": HTTP_CREATE_OK,
                "data": marshal(movie_order, order_fields),
                "response": response
            }


class MovieOrderResource(Resource):  # 此接口用于修改订单表信息,修改订单信息需要高级权限用户才能完成
    @required_permission(VIP_USER)
    def put(self, order_id):
        print(order_id)
        return {"msg": "change  success"}


if __name__ == "__main__":
    pass
